from django.shortcuts import render, redirect, reverse
from django.db.models import Count
from django.db.models import Q
from task_market.models import Check_result, Taskdata, TaskApplication, Task
from user_mng.models import users
from django.db.models import Avg


# Create your views here.

# views.py


def user_market(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    item = request.GET.get('search')
    if not request.session.get('account'):  # 判断是否登录 显示不同按键
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]
        typee = user_list[request.session.get('account')][1]
    # 获取user_type为1的所有用户信息
    users_list = users.objects.filter(user_type=1)
    for user in users_list:
        user_id_yige = user.user_id
        # 获取特定user_id的所有相关taskdata_id
        taskdata_ids = Taskdata.objects.filter(
            taskdata_assign=user_id_yige, taskdata_status='1'
        ).values_list("id", flat=True)

        # 计算该user_id的平均check_score
        sum_score = 0

        for taskdata_id in taskdata_ids:
            try:
                check_result = Check_result.objects.get(Taskdata_id=taskdata_id)
                sum_score += check_result.Check_score
                # print("------------",check_result.Check_score)
            except Check_result.DoesNotExist:

                sum_score += 0  # 设置默认值为0

            # sum_score += Check_result.objects.get(Taskdata_id=taskdata_id).Check_score
            # print("----------",Check_result.objects.filter(Taskdata_id=taskdata_id).values_list('Check_score', flat=True).first())
            # sum_score = int(Check_result.objects.filter(Taskdata_id=taskdata_id).values_list('Check_score', flat=True).first()) + sum_score
        if len(taskdata_ids) == 0:
            avg_score = 100
        else:
            # print("----------",len(taskdata_ids))
            avg_score = sum_score / len(taskdata_ids)
        user.user_score = "{:.3f}".format(avg_score)
        user.save()

    if not item:
        return render(request, "task_market/worker_market.html",
                      {"users_list": users_list, 'name': name, 'staues': staue, 'type': typee})
    else:
        task_list = Task.objects.filter(task_name__icontains=item, task_status=0)
        return render(request, 'manager/all_grid_admin.html',
                      {'tasks': task_list, 'name': name, 'staues': staue, 'conditions': 'checking', 'type': typee})


def detail_everytask(request, id):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    item = request.GET.get('search')
    if not request.session.get('account'):  # 判断是否登录 显示不同按键
        staue = 'login'
        name = '请登录'
        type = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]
        type = user_list[request.session.get('account')][1]
    # 找出在TaskApplication表中，Task_id为1的所有Task_applier_id和Apply_volumn
    task_applications = TaskApplication.objects.filter(Task_id=id).values(
        "Task_applier_id", "Apply_volumn"
    )
    result = []

    for task_application in task_applications:
        task_applier_id = task_application["Task_applier_id"]
        apply_volumn = task_application["Apply_volumn"]
        user = users.objects.get(user_id=task_applier_id)
        user_name = user.user_name
        # 统计taskdata_task_id为1，taskdata_assign为Task_applier_id，而taskdata_result不为空的数量
        taskdata_matchs = Taskdata.objects.filter(
            taskdata_task_id=id,
            taskdata_assign=task_applier_id,
        )
        sum_of_match = 0
        for match in taskdata_matchs:
            if match.taskdata_status == '1':
                sum_of_match += 1

        count = sum_of_match
        # 记录taskdata_content和taskdata_result
        data_list = Taskdata.objects.filter(
            taskdata_task_id=id, taskdata_assign=task_applier_id
        ).values_list("taskdata_content", "taskdata_result")

        existing_item = next((item for item in result if item["Task_applier_id"] == task_applier_id), None)
        # if existing_item:
        #     existing_item["Apply_volumn"] += apply_volumn
        #     existing_item["Count"] += count
        # else:
        result.append(
            {
                "Task_applier_id": task_applier_id[0:1],
                "Name": user_name,
                "Apply_volumn": apply_volumn,
                "Count": count,
                "Data_List": data_list,
            }
        )
    print(result)
    task = Task.objects.get(id=id)
    worker_sum = len(result)  # 对应task_id的申请人数
    apply_volumn_sum = sum([x["Apply_volumn"] for x in result])  # 对应task_id的申请总数
    task_count = Taskdata.objects.filter(taskdata_task_id = id).count()  # 找出这个任务一共有多少数据
    return render(request, "manager/task_detail.html",
                  locals())


def check(request, task_id, res):
    task = Task.objects.get(id=task_id)
    if res == 0:
        task.task_status = 1
    elif res == 1:
        task.task_status = 3
    task.save()
    return redirect(reverse('manager:task_admin', kwargs={'condition': 'checking'}))


def check_score(request, id):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    item = request.GET.get('search')
    if not request.session.get('account'):  # 判断是否登录 显示不同按键
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]
        typee = user_list[request.session.get('account')][1]
    show_items = int(request.GET.get('show_items', 10))
    task = Task.objects.get(id=id)
    assign_data_all = Taskdata.objects.filter(taskdata_task_id=id).count()
    assign_data_anno = Taskdata.objects.filter(taskdata_task_id=id,
                                               taskdata_status='1').count()
    # print(type(assign_data_all))
    perc_anno = str(assign_data_anno / assign_data_all * 100)[:5] + '%'
    if request.method == 'GET':
        show_items = int(request.GET.get('show_items', 10))  # 获取选择展示的数据条数，默认为10
        taskdata = Taskdata.objects.filter(taskdata_task_id=id, taskdata_status='1').exclude(
            taskdata_id__in=Check_result.objects.values("Taskdata_id"))[:show_items]
        # taskdata = Taskdata.objects.filter(taskdata_task_id=id)[:show_items]
    if request.method == 'POST':
        scores = request.POST.getlist("scores[]")
        ids = Taskdata.objects.filter(taskdata_task_id=id).values_list('id', flat=True)[:show_items]
        length = len(scores)
        for i in range(length):
            check_result = Check_result.objects.create(
                Taskdata_id=ids[i], Check_score=int(scores[i])
            )
            check_result.save()
        return redirect(reverse('manager:task_admin', kwargs={'condition': 'finished'}))
    if not item:

        return render(request, "manager/score_form.html",
                      {"taskdata": taskdata, 'task_id': id, 'show_items': show_items, 'name': name, 'staues': staue,
                       'task': task, 'type': typee, 'all_assign_num': assign_data_all,
                       'anno_assign_num': assign_data_anno,
                       'perc_anno': perc_anno})
    else:
        task_list = Task.objects.filter(task_name__icontains=item, task_status=1)
        return render(request, 'manager/all_grid_admin.html',
                      {'tasks': task_list, 'name': name, 'staues': staue, 'conditions': 'finished', 'type': typee})


def task_admin(request, condition):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    item = request.GET.get('search')
    if not request.session.get('account'):  # 判断是否登录 显示不同按键
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]
        typee = user_list[request.session.get('account')][1]
    if not item:
        if condition == 'checking':
            task_list = Task.objects.filter(task_status=0)
        elif condition == 'checked':
            task_list = Task.objects.filter(Q(task_status=1) | Q(task_status=2) | Q(task_status=4))
        elif condition == 'finished':
            task_list = Task.objects.filter(Q(task_status=1) | Q(task_status=2) | Q(task_status=4))
    else:
        if condition == 'checking':
            task_list = Task.objects.filter(task_name__icontains=item, task_status=0)
        elif condition == 'checked':
            task_list = Task.objects.filter(task_name__icontains=item).filter(
                Q(task_status=1) | Q(task_status=2) | Q(task_status=4))
        elif condition == 'finished':
            task_list = Task.objects.filter(task_name__icontains=item).filter(
                Q(task_status=1) | Q(task_status=2) | Q(task_status=4))

    return render(request, 'manager/all_grid_admin.html',
                  {'tasks': task_list, 'name': name, 'staues': staue, 'conditions': condition, 'type': typee})


def task_check(request, id):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    item = request.GET.get('search')
    if not request.session.get('account'):
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]  # name
        typee = user_list[request.session.get('account')][1]
    if not item:
        content_list = Taskdata.objects.all()
        task_list = Task.objects.all()
        content_detail = []
        for content in content_list:  # 找到该任务的10条数据
            if id == int(content.taskdata_task_id):
                content_detail.append(content)
            if len(content_detail) == 10:
                break
        # print(content_detail)
        for task in task_list:
            if id == task.id:
                task_detail = task  # 找到该单个任务的信息
        if not request.session.get('account'):
            return redirect('task_market:unaccessible')
        elif user_list[request.session.get('account')][1] == 0:
            return render(request, 'manager/task_check.html',
                          {'content_details': content_detail, 'task_details': task_detail, 'name': name,
                           'staues': staue, 'type': typee})
    else:
        task_list = Task.objects.filter(task_name__icontains=item, task_status=0)
        return render(request, 'manager/all_grid_admin.html',
                      {'tasks': task_list, 'name': name, 'staues': staue, 'type': typee, 'conditions': 'checking'})


def confirm_end(request, task_id):
    task = Task.objects.get(id=task_id)
    task.task_status = 2
    task.save()

    # money
    pay_worker = TaskApplication.objects.filter(Task_id=task_id)
    for worker in pay_worker:
        num = Taskdata.objects.filter(taskdata_task_id=task_id, taskdata_assign=worker.Task_applier_id,
                                      taskdata_status='1').count()
        user = users.objects.get(user_id=worker.Task_applier_id)
        user.user_money += num * Task.objects.get(id=worker.Task_id).task_salary
        user.save()
    return redirect(reverse('manager:check_score', kwargs={'id': task_id}))


def cancel_end(request, task_id):
    task = Task.objects.get(id=task_id)
    task.task_status = 1
    task.save()
    return redirect(reverse('manager:check_score', kwargs={'id': task_id}))
